package pipeline;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/3/17.
 */
public abstract class AbstractPipe<IN,OUT> implements Pipe<IN,OUT> {

    protected volatile Pipe<?,?> nextPipe = null;

    protected volatile PipeContext pipeContext;

    @Override
    public void init(PipeContext pipeContext) {
        this.pipeContext = pipeContext;
    }

    @Override
    public void setNextPipe(Pipe<?, ?> nextPipe) {
        this.nextPipe = nextPipe;
    }

    @Override
    public void shutdown(long timeout, TimeUnit timeUnit) {
        //do nothing...
    }

    protected abstract OUT doProcess(IN input) throws PipeException;

    public void process(IN input) throws InterruptedException{
        try{
            OUT out=doProcess(input);
            if(null != nextPipe){
                if(null != out ){
                    ((Pipe<OUT,?>) nextPipe).process(out);
                }
            }
        }catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }catch (PipeException e){
            pipeContext.handleError(e);
        }
    }

}
